package com.simemg.reader.slice;

import com.simemg.reader.ResourceTable;
import com.simemg.reader.fraction.novel.MenuFraction;
import com.simemg.reader.fraction.novel.SettingFraction;
import com.simemg.reader.model.Loading;
import com.simemg.reader.store.Book;
import com.simemg.reader.store.Page;
import com.simemg.reader.store.Theme;
import com.simemg.reader.utils.*;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.ability.fraction.FractionScheduler;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.window.service.Window;

import java.util.ArrayList;
import java.util.List;

public class NovelSlice extends  AbilitySlice {
    private boolean isMenu = false;
    private boolean isSetting = false;

    private Theme theme;
    private Book book;
    private Page page;

    public static List<Integer> colorList = new ArrayList<Integer>() {{
        add(ResourceTable.Color_white);
        add(ResourceTable.Color_green);
        add(ResourceTable.Color_yellow);
        add(ResourceTable.Color_pink);
        add(ResourceTable.Color_blue);
        add(ResourceTable.Color_brown);
        add(ResourceTable.Color_black);
    }};


    private MenuFraction menu;
    private SettingFraction setting;

    private StackLayout layout;
    private ScrollView scroll;
    private Text title;
    private Text content;

    public Book getBook() {
        return book;
    }
    public Page getPage() {
        return page;
    }
    public Theme getTheme_() {
        return theme;
    }


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_slice_novel);

        initComponent();
        loadData(intent);
        addComponentListen();
    }

    public void onActive() {
        book = StoreUtil.searchBook(book.getBookID());
        loadPage(book, book.getNowNum());
        menu.updateProgress();
    }

    void initComponent(){
        layout = (StackLayout) findComponentById(ResourceTable.Id_layout);
        scroll = (ScrollView) findComponentById(ResourceTable.Id_scroll);
        title = (Text) findComponentById(ResourceTable.Id_title);
        content = (Text) findComponentById(ResourceTable.Id_content);

        menu = new MenuFraction(this);
        setting = new SettingFraction(this);

        ((FractionAbility) getAbility()).getFractionManager().startFractionScheduler()
                .add(ResourceTable.Id_layout, menu)
                .add(ResourceTable.Id_layout, setting)
                .submit();
        ((FractionAbility) getAbility()).getFractionManager().startFractionScheduler()
                .hide(menu).hide(setting)
                .submit();
    }

    void loadData(Intent intent) {
        int bookID = (Integer) RouterUtil.getData(intent);
        book = StoreUtil.searchBook(bookID);
        loadPage(book, book.getNowNum());
        theme = StoreUtil.getTheme();
    }

    void loadPage(Book book, int num) {
        Loading.show(layout);
        page = StoreUtil.readPage(book, num);
        if (page == null) return ;
        title.setText(page.getTitle());
        if (page.getCache() == null || page.getContent() == null || page.getContent().equals("")) {
            RequestUtil.Do(SpiderUtil.getSearchBookPage(page))
                    .onSuccess((RequestUtil.CallBackObject) (result)->{
                        String contentStr = (String) result;
                        if (contentStr != null) {
                            StoreUtil.savePage(page, contentStr);
                            content.setText(contentStr);
                        }
                        Loading.hide(layout);
                    })
                    .execute();
        }
        else {
            content.setText(page.getContent());
            Loading.hide(layout);
        }

        tryLoadNextPage(book, num);
    }

    void tryLoadNextPage(Book book, int num) {
        if (book.getMaxNum() == num) return;
        Page nextPage = StoreUtil.searchPage(book, num + 1);
        if (nextPage != null && nextPage.getCache() == null) {
            RequestUtil.Do(SpiderUtil.getSearchBookPage(nextPage))
                    .onSuccess((RequestUtil.CallBackObject) (result)->{
                        String contentStr = (String) result;
                        if (contentStr != null) {
                            StoreUtil.savePage(nextPage, contentStr);
                        }
                    })
                    .execute();
        }
    }


    void addComponentListen() {
        scroll.setTouchEventListener((component, touchEvent) -> {
            TouchUtil.Tag tag = TouchUtil.listen(component, touchEvent);
            if (tag.isClickMiddle()) onClickMiddle();
            if (tag.isUpLastPage()) onLast();
            if (tag.isDownNextPage()) onNext();
            return true;
        });
    }

    void onClickMiddle() {
        FractionScheduler scheduler = ((FractionAbility) getAbility()).getFractionManager().startFractionScheduler();
        if (isMenu || isSetting) {
            scheduler = scheduler.hide(menu).hide(setting);
            isMenu = false;
            isSetting = false;
            updateTheme();
        }
        else {
            scheduler = scheduler.show(menu);
            isMenu = true;
            setStatusBarColor(6);
        }
        scheduler.submit();
    }

    public void onSetting() {
        isSetting = true;
        ((FractionAbility) getAbility()).getFractionManager().startFractionScheduler()
                .show(setting).hide(menu).submit();
        isMenu = false;
        updateTheme();
    }

    public void onNext() {
        if (book.getNowNum().equals(book.getMaxNum())) return;
        loadPage(book, book.getNowNum() + 1);
        menu.updateProgress();
        scroll.scrollTo(0,0);
    }

    public void onLast() {
        if (book.getNowNum() == 0) return;
        loadPage(book, book.getNowNum() - 1);
        menu.updateProgress();
        scroll.scrollTo(0, content.getHeight());
    }

    public void updateTheme() {
        if (theme.isNightMode()) {
            setStatusBarColor(6);
            setScrollBackgroundColor(6);
            title.setTextColor(new Color(ColorUtil.get(this, ResourceTable.Color_night)));
            content.setTextColor(new Color(ColorUtil.get(this, ResourceTable.Color_night)));
        }
        else {
            if (!isMenu && !isSetting) setStatusBarColor(theme.getColor());
            setScrollBackgroundColor(theme.getColor());
            title.setTextColor(new Color(ColorUtil.get(this, ResourceTable.Color_day)));
            content.setTextColor(new Color(ColorUtil.get(this, ResourceTable.Color_day)));
        }
        title.setTextSize(theme.getTextSize() + 6, Text.TextSizeType.VP);
        content.setTextSize(theme.getTextSize() + 4, Text.TextSizeType.VP);
        content.setLineSpacing(10 * theme.getLineSize(), 1);
        StoreUtil.updateTheme(theme);
    }

    void setStatusBarColor(int i) {
        Window window = getWindow();
        window.setStatusBarColor(ColorUtil.get(this, colorList.get(i)));
        window.setStatusBarVisibility(Component.VISIBLE);
    }

    void setScrollBackgroundColor(int i) {
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setRgbColor(ColorUtil.getRbg(this, colorList.get(i)));
        scroll.setBackground(shapeElement);
    }

}
